//
//  WPMoreDetailkidVC.m
//  wobingwoyi
//
//  Created by WGP on 2016/12/8.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPMoreDetailkidVC.h"
#import "WPDiseaseTypesVC.h"

#define MaxSCale 2.0  //最大缩放比例
#define MinScale 1.0  //最小缩放比例
#define kHeightScale ((SCREEN_HEIGHT-107)/560)
#define kWidthScale (self.view.frame.size.width/375)

@interface WPMoreDetailkidVC ()<UIScrollViewDelegate>

@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)UIImageView *imageView;
@property(nonatomic,strong)UIImageView *bgImageView;
@property(nonatomic,assign)CGFloat totalScale;
@property(nonatomic,strong)UIView *bottomView;
@property(nonatomic,strong)UIButton *coverBtn;

@property(nonatomic,strong)NSMutableArray *diseasesArr;

@end

@implementation WPMoreDetailkidVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.totalScale = 1.0;
    [self setupUI];
}

-(void)setupUI
{
    [self bgImageView];
    [self scrollView];
    [self imageView];
}

-(UIScrollView *)scrollView
{
    if (_scrollView == nil)
    {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.delegate = self;
        _scrollView.backgroundColor = [UIColor clearColor];
        [_scrollView setMinimumZoomScale:1.0];
        [_scrollView setMaximumZoomScale:2.0f];
        
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        
        _scrollView.bounces = NO;
        _scrollView.bouncesZoom = NO;
        
        CGSize newSize = [UIImage imageNamed:@"body"].size;
        //_scrollview可以拖动的范围
        [_scrollView setContentSize:newSize];
        [self.view addSubview:_scrollView];
        
        [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.edges.equalTo(self.view);
        }];
    }
    return _scrollView;
}

-(UIImageView *)bgImageView
{
    if (_bgImageView == nil)
    {
        _bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bgCase"]];
        [self.view addSubview:_bgImageView];
        
        [_bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        
    }
    return _bgImageView;
}

-(UIImageView *)imageView
{
    if (_imageView == nil)
    {
        UIImage *image = [UIImage imageNamed:@"kid_body"];
        
        _imageView = [[UIImageView alloc] initWithImage:image];
        _imageView.userInteractionEnabled = YES;
        //        _imageView.backgroundColor = [UIColor orangeColor];
        [self.scrollView addSubview:_imageView];
        
        CGFloat imageScale = image.size.width/image.size.height;
        
        CGFloat imageH = (SCREEN_HEIGHT-108)-8*kHeightScale;
        CGFloat imageW = imageH * imageScale;
        CGFloat imageX = (self.view.bounds.size.width-imageW)*0.5;
        CGFloat imageY = (SCREEN_HEIGHT-108) - imageH;
        
        _imageView.frame = CGRectMake(imageX, imageY, imageW, imageH);
        
        //        NSLog(@"%@",NSStringFromCGRect(_imageView.frame));
        // 单击
        UITapGestureRecognizer *SingleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resetImage:)];
        SingleTapGesture.numberOfTapsRequired = 1;//tap次数
        SingleTapGesture.numberOfTouchesRequired = 1;
        [_imageView addGestureRecognizer:SingleTapGesture];
        
        UITapGestureRecognizer* tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesAction:)];//给imageview添加tap手势
        tap.numberOfTapsRequired = 2;//双击图片执行tapGesAction
        _imageView.userInteractionEnabled=YES;
        [_imageView addGestureRecognizer:tap];
        
        // 关键在这一行，如果双击确定偵測失败才會触发单击
        [SingleTapGesture requireGestureRecognizerToFail:tap];
    }
    return _imageView;
}

-(UIView *)bottomView
{
    if (_bottomView == nil)
    {
        _bottomView  = [UIView new];
        _bottomView.bounds = CGRectMake(0, 0, SCREEN_WIDTH, 150*kHeightScale);
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"moreDetailBg"]];
        [_bottomView addSubview:imageView];
        imageView.frame = _bottomView.bounds;
        
        UIView *topView = [UIView new];
        topView.backgroundColor = [UIColor whiteColor];
        [_bottomView addSubview:topView];
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(_bottomView);
            make.top.equalTo(_bottomView).offset(15*kHeightScale);
            make.height.mas_equalTo(45*kHeightScale);
        }];
        
        UIImageView *topline = [UIImageView lineImageView];
        [topView addSubview:topline];
        [topline mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(topView);
            make.height.mas_equalTo(0.5);
        }];
        
        UIImageView *bottomline = [UIImageView lineImageView];
        [topView addSubview:bottomline];
        [bottomline mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.left.right.equalTo(topView);
            make.height.mas_equalTo(0.5);
        }];
        
        UILabel *diseaseLabel = [UILabel new];
        diseaseLabel.textColor = GLobalFontColor;
        diseaseLabel.font = [UIFont systemFontOfSize:15];
        diseaseLabel.text  = @"头部疾病";
        [topView addSubview:diseaseLabel];
        [diseaseLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(topView);
            make.left.equalTo(topView).offset(15);
        }];
        
        UILabel *tipLabel = [UILabel new];
        tipLabel.textColor = GloballightFontColor;
        tipLabel.font = [UIFont systemFontOfSize:13];
        tipLabel.text = @"(请选择疾病)";
        [topView addSubview:tipLabel];
        [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(topView);
            make.left.equalTo(diseaseLabel.mas_right).offset(10);
        }];
        
        UILabel *rightTipLabel = [UILabel new];
        rightTipLabel.textColor = GlobalColor;
        rightTipLabel.text = @"上下滑动查看更多";
        rightTipLabel.font = [UIFont systemFontOfSize:12];
        [topView addSubview:rightTipLabel];
        [rightTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(topView);
            make.right.equalTo(topView).offset(-10);
        }];
        
        UIScrollView *bottomScrollView = [[UIScrollView alloc] init];
        bottomScrollView.backgroundColor = [UIColor whiteColor];
        bottomScrollView.bounces = NO;
        [_bottomView addSubview:bottomScrollView];
        [bottomScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(_bottomView);
            make.top.equalTo(topView.mas_bottom);
        }];
        
        NSLog(@"******%zd",self.diseasesArr.count);
        for (int i = 0; i < self.diseasesArr.count; i++)
        {
            CGFloat btnW = SCREEN_WIDTH / 3.0;
            NSString *str = self.diseasesArr[i];
            UIButton *diseaseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [diseaseBtn setTitle:str forState:UIControlStateNormal];
            [diseaseBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
            [diseaseBtn setBackgroundImage:[UIImage imageNamed:@"diseaseBtn_bg"] forState:UIControlStateNormal];
            diseaseBtn.titleLabel.font = [UIFont systemFontOfSize:14];
            [diseaseBtn addTarget:self action:@selector(diseaseBtnDidClick:) forControlEvents:UIControlEventTouchDown];
            diseaseBtn.tag = i;
            int row = i / 3;
            int low = i % 3;
            diseaseBtn.frame = CGRectMake(low*btnW, row*45, btnW, 45);
            [bottomScrollView addSubview:diseaseBtn];
        }
        
        if(self.diseasesArr.count%3)
        {
            bottomScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, (self.diseasesArr.count / 3 + 1)*45);
        }
        else
        {
            bottomScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, (self.diseasesArr.count / 3)*45);
        }

    }
    return _bottomView;
}

//单击恢复视图
- (void)resetImage:(UITapGestureRecognizer *)recognizer
{
    NSString *url = @"diseaseCategory/getCategory.do";
    
    NSDictionary *dict = @{@"sex":@"kid"};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if([responseObject[@"result"] isEqualToString:@"success"])
        {
            [self.diseasesArr removeAllObjects];
            
            for (NSString *str in responseObject[@"detail"])
            {
                [self.diseasesArr addObject:str];
            }
            WPLog(@"%@",self.diseasesArr);
            [self bodyBtnDidClick];
        }
        else
        {
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                [self illegalLoginWithSuccessBlock:^{
                    //提示账号过期点击确定之后
                    
                }];
            }
            else
            {
                [self showErrorInfoWithStatus:@"加载失败"];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

-(void)tapGesAction:(UIGestureRecognizer*)gestureRecognizer//手势执行事件
{
    
    float newScale = 0;
    //zoomScale这个值决定了contents当前扩展的比例
    if (self.scrollView.zoomScale > 1.0)
    {
        newScale = 1.0;
    }
    else
    {
        newScale = 2.0;
    }
    
    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
    [self.scrollView zoomToRect:zoomRect animated:YES];
}

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center
{
    CGRect zoomRect;
    zoomRect.size.height = self.scrollView.frame.size.height / scale;
    zoomRect.size.width  = self.scrollView.frame.size.width  / scale;
    zoomRect.origin.x = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);
    
    return zoomRect;
}

#pragma mark - 按钮点击事件
-(void)bodyBtnDidClick
{
    UIButton *coverBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.coverBtn = coverBtn;
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    coverBtn.backgroundColor = [UIColor clearColor];
    [keyWindow addSubview:coverBtn];
    coverBtn.frame = [UIScreen mainScreen].bounds;
    [coverBtn addTarget:self action:@selector(coverBtnDidClick:) forControlEvents:UIControlEventTouchDown];
    
    [coverBtn addSubview:self.bottomView];
    self.bottomView.frame = CGRectMake(0, SCREEN_HEIGHT-self.bottomView.bounds.size.height, SCREEN_WIDTH, self.bottomView.bounds.size.height);
}

-(void)coverBtnDidClick:(UIButton *)btn
{
    [btn removeFromSuperview];
    self.bottomView = nil;
    btn = nil;
}

-(void)diseaseBtnDidClick:(UIButton *)btn
{
    [self coverBtnDidClick:self.coverBtn];
    //疾病点击
    WPDiseaseTypesVC *ccVC = [WPDiseaseTypesVC new];
    NSString *str = self.diseasesArr[btn.tag];
    ccVC.diseaseTitle = str;
    ccVC.isPop = YES;
    ccVC.isPartOfHuman = YES;
    [self.navigationController pushViewController:ccVC animated:YES];
}

#pragma mark - UIScrollView的代理方法
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    //目前contentsize的width是否大于原scrollview的contentsize，如果大于，设置imageview中心x点为contentsize的一半，以固定imageview在该contentsize中心。如果不大于说明图像的宽还没有超出屏幕范围，可继续让中心x点为屏幕中点，此种情况确保图像在屏幕中心。
    CGFloat xcenter = scrollView.center.x ;
    CGFloat ycenter = scrollView.center.y;
    
    xcenter = scrollView.contentSize.width > scrollView.frame.size.width ? scrollView.contentSize.width/2 : xcenter;
    
    ycenter = scrollView.contentSize.height > scrollView.frame.size.height ? scrollView.contentSize.height/2 : ycenter;
    [self.imageView setCenter:CGPointMake(xcenter, ycenter)];
}

-(NSMutableArray *)diseasesArr
{
    if (_diseasesArr == nil)
    {
        _diseasesArr = [NSMutableArray array];
    }
    return _diseasesArr;
}

@end
